<template>
	<el-drawer v-model="show" title="附件上传" size="50%">
		<!-- 上传配置信息展示 -->
		<div class="upload-config-info" v-if="attachmentStore.uploadConfig">
			<el-alert type="info" :closable="false" :show-icon="false">
				<div class="config-content">
					<div class="config-item">
						<label>最大文件大小：</label>
						<span class="config-value">{{ attachmentStore.formattedMaxSize }}</span>
					</div>
					<div class="config-item">
						<label>支持文件类型：</label>
						<div class="file-types">
							<el-tag v-for="(typeInfo, key) in attachmentStore.uploadConfig.allowedFileTypes" :key="key"
								class="type-tag" type="success" size="small">
								{{ typeInfo.name }}：{{ typeInfo.ext.join(', ') }}
							</el-tag>
						</div>
					</div>
				</div>
			</el-alert>
		</div>

		<!-- 上传组件 -->
		<el-upload show-file-list list-type="text" :on-success="onSuccess" :on-error="onError" :headers="headers"
			class="upload-demo" drag :action="uploadUrl" multiple>
			<el-icon class="el-icon--upload"><upload-filled /></el-icon>
			<div class="el-upload__text">
				文件拖入此处, 或 <em>点击选择文件</em>
			</div>
			<template #tip>
				<div class="el-upload__tip" v-if="attachmentStore.uploadConfig">
					支持{{ attachmentStore.allowedExtensions }}文件，单个文件最大{{ attachmentStore.formattedMaxSize }}
				</div>
			</template>
		</el-upload>
	</el-drawer>
</template>

<script>
import { ElMessage } from 'element-plus'
import { useAccountStore } from '../../../../stores/account'
import { useAttachmentStore } from '../../../../stores/attachment'
import { apiConfig } from '../../../../utils/config'
export default {
	data() {
		return {
			show: false,
		}
	},
	methods: {
		open() {
			this.show = true;
		},
		onSuccess(response, uploadFile, uploadFiles) {
			if (response.code != 200) {
				ElMessage.error(`文件:${uploadFile.name} - 上传失败,${response.message}`)
				uploadFile.status = 'fail'
				return
			}
			ElMessage.success(`文件:${uploadFile.name} - 上传成功`)
			this.$emit('refresh')
		},
		onError(error, uploadFile, uploadFiles) {
			console.log(error)
			ElMessage.error(`文件:${uploadFile.name} - 上传失败,${error}`)
		}
	},
	computed: {
		accountStore() {
			return useAccountStore()
		},
		attachmentStore() {
			return useAttachmentStore()
		},
		headers() {
			return {
				Authorization: `Bearer ${this.accountStore.token}`,
			}
		},
		uploadUrl() {
			return apiConfig.baseURL + "/sunAdmin/attachment/upload"
		}
	}
}
</script>

<style scoped>
.upload-config-info {
	margin-bottom: 10px;
}

.config-content {
	display: flex;
	flex-direction: column;
	gap: 6px;
}

.config-item {
	display: flex;
	align-items: flex-start;
	gap: 8px;
}

.config-item label {
	font-weight: bold;
	color: #606266;
	min-width: 100px;
	flex-shrink: 0;
}

.config-value {
	color: #409EFF;
	font-weight: bold;
}

.file-types {
	display: flex;
	flex-wrap: wrap;
	gap: 8px;
	flex: 1;
}

.type-tag {
	margin: 0;
}

.upload-demo {}
</style>